package com.muyi.controller;

import com.muyi.pojo.dto.PageBean;
import com.muyi.pojo.entity.Result;
import com.muyi.pojo.entity.User;
import com.muyi.utils.MD5Util;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "用户模块")
@CrossOrigin
@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private com.muyi.service.UserService UserService;

//    /**
////     * 查询用户数据
////     * @return
////     */
////    @ApiOperation(value = "查询全部用户")
////    @GetMapping
////    public Result list(){
////        log.info("查询全部用户数据");
////        //调用service查询用户数据
////        List<User> UserList =  UserService.list();
////        return Result.success(UserList);
////    }

    @ApiOperation(value = "分页查询用户")
    @GetMapping
    public Result page(@RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "5") Integer pageSize,
                       String nickname, String gender, String career_direction){
        log.info("分页查询用户, 参数: {},{},{},{},{}",page,pageSize,nickname,gender,career_direction);
        //调用service分页查询
        PageBean pageBean = UserService.page(page,pageSize,nickname,gender,career_direction);
        return Result.success(pageBean);
    }


    /**
     * 删除用户
     * @return
     */
    @ApiOperation(value = "删除用户")
    @DeleteMapping("/{user_id}")
    public Result delete(@PathVariable Integer user_id){
        log.info("根据user_id删除用户:{}",user_id);
        //调用service删除用户
        UserService.delete(user_id);
        return Result.success();
    }


    /**
     * 新增用户
     * @return
     */
    @ApiOperation(value = "新增用户")
    @PostMapping
    public Result add(@RequestBody User User){
        log.info("新增用户: {}" , User);
        // 密码加密
        String s1 = MD5Util.getMD5String(User.getPassword());
        String password = MD5Util.getMD5String(s1 + MD5Util.SALT);
        User.setPassword(password);
        //调用service新增用户
        UserService.add(User);
        return Result.success();
    }

    @ApiOperation(value = "更新用户")
    @PutMapping
    public Result update(@RequestBody User User){
        log.info("更新用户信息 : {}", User);
        // 密码加密
        String s1 = MD5Util.getMD5String(User.getPassword());
        String password = MD5Util.getMD5String(s1 + MD5Util.SALT);
        User.setPassword(password);
        UserService.update(User);
        return Result.success();
    }

    // 根据user_id查询用户
    @ApiOperation(value = "根据用户id查询用户")
    @GetMapping("/{user_id}")
    public Result getByUserId(@PathVariable Integer user_id){
        log.info("根据user_id查询用户, user_id:{}",user_id);
        User User = UserService.getByUserId(user_id);
        return Result.success(User);
    }
}
